/**
 * Database access object definition
 * Usage: 1. ResultSet rs = DBAccessSingleton.getInstance().getStatement().executeQuery("SELECT * FROM carriage_rate");
 *        2. Connection con = DBAccessSingleton.getInstance().getConnection();
 * Please don't not try to initialize this class, just call DBAccessSingleton.getInstance() at anywhere at anytime
 * @author james
 */

package digitshoplogic;

// We need to import the java.sql package to use JDBC
import java.sql.*;

// for the login window
import java.util.logging.Level;
import java.util.logging.Logger;


public class DBAccessSingleton {
    private static Connection con;
    private Statement statement;

    private DBAccessSingleton() {
        System.out.println("Hello Jdbc!");
        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            con = DriverManager.getConnection("jdbc:mysql://localhost/shop_db", "root", "");
            //set auto commit is false;
            //con.setAutoCommit(false);
            statement = con.createStatement();

        } catch (SQLException ex) {
            Logger.getLogger(DBAccessSingleton.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static DBAccessSingleton getInstance() throws SQLException {
        if(DBAccessSingletonHolder.INSTANCE == null ||con == null || con.isClosed()){
            DBAccessSingletonHolder.INSTANCE = new DBAccessSingleton();
        }
        return DBAccessSingletonHolder.INSTANCE;
    }

    private static class DBAccessSingletonHolder {
        private static DBAccessSingleton INSTANCE = new DBAccessSingleton();
    }
    /**
     * Get the JDBC connection Singleton object
     * @return the Singleton connection object
     */
    public Connection getConnection(){
        return this.con;
    }
    /**
     * Get the Statement object
     * @return the Statement object to execute SQL command
     */
    public Statement getStatement(){
        return this.statement;
    }
 }
